<template>
  <div class="ranking-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>榜单管理</h2>
      <p>管理榜单数据，支持刷新、统计、查询和健康检查</p>
    </div>

    <!-- 操作按钮区 -->
    <div class="action-bar">
      <el-button
        type="primary"
        :icon="Refresh"
        :loading="refreshLoading"
        @click="refreshRankings"
      >
        刷新排行榜数据
      </el-button>

      <el-button
        type="info"
        :icon="DataAnalysis"
        :loading="statisticsLoading"
        @click="loadStatistics"
      >
        获取统计信息
      </el-button>

      <el-button
        type="success"
        :icon="Monitor"
        :loading="healthLoading"
        @click="checkHealth"
      >
        健康检查
      </el-button>

      <el-button
        type="warning"
        :icon="Warning"
        :loading="clearLoading"
        @click="clearRankings"
      >
        清空排行榜
      </el-button>
    </div>

    <!-- 统计信息卡片 -->
    <div v-if="statistics" class="statistics-section">
      <el-row :gutter="20">
        <el-col :span="5">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value">
                {{ statistics.articleRankingCount || 0 }}
              </div>
              <div class="stat-label">文章榜记录数</div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="5">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value">
                {{ statistics.authorRankingCount || 0 }}
              </div>
              <div class="stat-label">作者榜记录数</div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="5">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value">
                {{ statistics.collectionRankingCount || 0 }}
              </div>
              <div class="stat-label">收藏榜记录数</div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="5">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value">
                {{ statistics.totalRankingCount || 0 }}
              </div>
              <div class="stat-label">总记录数</div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value small">
                {{ formatTime(statistics.lastUpdateTime) }}
              </div>
              <div class="stat-label">最后更新</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 排名查询 -->
    <el-card class="query-section">
      <template #header>
        <div class="card-header">
          <span>排名查询</span>
        </div>
      </template>

      <el-form :model="queryForm" inline>
        <el-form-item label="目标ID">
          <el-input
            v-model="queryForm.targetId"
            placeholder="请输入文章/作者ID"
            type="number"
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="榜单类型">
          <el-select
            v-model="queryForm.rankingType"
            placeholder="请选择榜单类型"
            style="width: 150px"
          >
            <el-option label="文章榜" value="ARTICLE" />
            <el-option label="作者榜" value="AUTHOR" />
            <el-option label="收藏榜" value="COLLECTION" />
          </el-select>
        </el-form-item>

        <el-form-item label="榜单维度">
          <el-select
            v-model="queryForm.dimension"
            placeholder="请选择维度"
            style="width: 120px"
          >
            <el-option label="综合榜" value="OVERALL" />
            <el-option label="分类榜" value="CATEGORY" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="queryForm.dimension === 'CATEGORY'" label="分类ID">
          <el-input
            v-model="queryForm.categoryId"
            placeholder="请输入分类ID"
            type="number"
            style="width: 150px"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :icon="Search"
            :loading="queryLoading"
            :disabled="!queryForm.targetId || !queryForm.rankingType"
            @click="queryRank"
          >
            查询排名
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 查询结果 -->
      <div v-if="rankResult" class="rank-result">
        <el-alert
          :title="`目标 ${rankResult.targetId} 在 ${getRankingTypeName(rankResult.rankingType)} - ${getDimensionName(rankResult.dimension)} 中的排名`"
          :type="rankResult.inRanking ? 'success' : 'warning'"
          :closable="false"
        >
          <template #default>
            <div class="rank-info">
              <span class="rank-label">排名：</span>
              <span
                class="rank-value"
                :class="{ 'not-in-rank': !rankResult.inRanking }"
              >
                {{
                  rankResult.inRanking ? `第 ${rankResult.rank} 名` : "不在榜"
                }}
              </span>
            </div>
          </template>
        </el-alert>
      </div>
    </el-card>

    <!-- 榜单操作 -->
    <el-card class="operation-section">
      <template #header>
        <div class="card-header">
          <span>榜单操作</span>
        </div>
      </template>

      <el-tabs v-model="activeTab">
        <!-- 移除榜单项 -->
        <el-tab-pane label="移除项" name="remove">
          <el-form :model="removeForm" inline>
            <el-form-item label="目标ID">
              <el-input
                v-model="removeForm.targetId"
                placeholder="请输入文章/作者ID"
                type="number"
                style="width: 200px"
              />
            </el-form-item>

            <el-form-item label="榜单类型">
              <el-select
                v-model="removeForm.rankingType"
                placeholder="请选择榜单类型"
                style="width: 150px"
              >
                <el-option label="文章榜" value="ARTICLE" />
                <el-option label="作者榜" value="AUTHOR" />
                <el-option label="收藏榜" value="COLLECTION" />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button
                type="danger"
                :icon="Delete"
                :loading="removeLoading"
                :disabled="!removeForm.targetId || !removeForm.rankingType"
                @click="removeRank"
              >
                从所有相关榜单移除
              </el-button>
            </el-form-item>
          </el-form>
          <el-alert
            title="移除说明"
            description="将从该类型的所有相关榜单（综合榜和所有分类榜）中移除指定目标"
            type="warning"
            :closable="false"
            style="margin-top: 16px"
          />
        </el-tab-pane>

        <!-- 更新榜单项 -->
        <el-tab-pane label="更新项" name="update">
          <el-form :model="updateForm" label-width="120px">
            <el-form-item label="目标ID" required>
              <el-input
                v-model="updateForm.targetId"
                placeholder="请输入文章/作者ID"
                type="number"
                style="width: 200px"
              />
            </el-form-item>

            <el-form-item label="榜单类型" required>
              <el-select
                v-model="updateForm.rankingType"
                placeholder="请选择榜单类型"
                style="width: 200px"
              >
                <el-option label="文章榜" value="ARTICLE" />
                <el-option label="作者榜" value="AUTHOR" />
                <el-option label="收藏榜" value="COLLECTION" />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                :icon="Edit"
                :loading="updateLoading"
                :disabled="!updateForm.targetId || !updateForm.rankingType"
                @click="updateRank"
              >
                更新榜单数据
              </el-button>
            </el-form-item>
          </el-form>
          <el-alert
            title="更新说明"
            description="从数据库获取最新数据并更新该目标在所有相关榜单中的排名"
            type="info"
            :closable="false"
            style="margin-top: 16px"
          />
        </el-tab-pane>

        <!-- 刷新指定榜单 -->
        <el-tab-pane label="刷新榜单" name="refresh">
          <el-form :model="refreshForm" inline>
            <el-form-item label="榜单类型">
              <el-select
                v-model="refreshForm.rankingType"
                placeholder="请选择榜单类型"
                style="width: 150px"
              >
                <el-option label="文章榜" value="ARTICLE" />
                <el-option label="作者榜" value="AUTHOR" />
                <el-option label="收藏榜" value="COLLECTION" />
              </el-select>
            </el-form-item>

            <el-form-item label="榜单维度">
              <el-select
                v-model="refreshForm.dimension"
                placeholder="请选择维度"
                style="width: 120px"
              >
                <el-option label="综合榜" value="OVERALL" />
                <el-option label="分类榜" value="CATEGORY" />
              </el-select>
            </el-form-item>

            <el-form-item
              v-if="refreshForm.dimension === 'CATEGORY'"
              label="分类ID"
            >
              <el-input
                v-model="refreshForm.categoryId"
                placeholder="请输入分类ID"
                type="number"
                style="width: 150px"
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                :icon="Refresh"
                :loading="refreshSingleLoading"
                :disabled="!refreshForm.rankingType || !refreshForm.dimension"
                @click="refreshSingleRanking"
              >
                刷新指定榜单
              </el-button>
            </el-form-item>
          </el-form>
          <el-alert
            title="刷新说明"
            description="从数据库重新计算并刷新指定榜单的所有数据"
            type="info"
            :closable="false"
            style="margin-top: 16px"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Refresh,
  DataAnalysis,
  Search,
  Delete,
  Edit,
  Monitor,
  Warning
} from "@element-plus/icons-vue";
import {
  refreshAllRankings,
  getAdminRankingStatistics,
  getRankingPosition,
  removeRankingItem,
  updateRankingItem,
  getRankingHealth,
  clearAllRankings,
  type RankingType,
  type RankingDimension
} from "@/api/ranking";

defineOptions({
  name: "RankingManagement"
});

// 加载状态
const refreshLoading = ref(false);
const statisticsLoading = ref(false);
const queryLoading = ref(false);
const removeLoading = ref(false);
const updateLoading = ref(false);
const healthLoading = ref(false);
const clearLoading = ref(false);

// 统计信息
const statistics = ref<any>(null);

// 查询表单
const queryForm = reactive({
  targetId: "",
  rankingType: "ARTICLE",
  dimension: "OVERALL",
  categoryId: ""
});

// 查询结果
const rankResult = ref<any>(null);

// 移除表单
const removeForm = reactive({
  targetId: "",
  rankingType: "ARTICLE"
});

// 更新表单
const updateForm = reactive({
  targetId: "",
  rankingType: "ARTICLE"
});

// 刷新表单
const refreshForm = reactive({
  rankingType: "ARTICLE",
  dimension: "OVERALL",
  categoryId: ""
});

// 单个榜单刷新加载状态
const refreshSingleLoading = ref(false);

// 当前标签页
const activeTab = ref("remove");

// 获取排行榜类型名称
const getRankingTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    ARTICLE: "文章榜",
    AUTHOR: "作者榜",
    COLLECTION: "收藏榜"
  };
  return typeMap[type] || type;
};

// 获取维度名称
const getDimensionName = (dimension: string) => {
  const dimensionMap: Record<string, string> = {
    OVERALL: "综合榜",
    CATEGORY: "分类榜"
  };
  return dimensionMap[dimension] || dimension;
};

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return "暂无";
  return time;
};

// 刷新排行榜数据
const refreshRankings = async () => {
  try {
    refreshLoading.value = true;

    await refreshAllRankings();

    ElMessage.success("排行榜数据刷新成功");

    // 刷新后重新获取统计信息
    await loadStatistics();
  } catch (error) {
    console.error("刷新排行榜数据失败:", error);
    ElMessage.error("刷新排行榜数据失败");
  } finally {
    refreshLoading.value = false;
  }
};

// 获取统计信息
const loadStatistics = async () => {
  try {
    statisticsLoading.value = true;

    const response = await getAdminRankingStatistics();

    // 提取data字段中的实际数据
    statistics.value = (response as any)?.data || response;
  } catch (error) {
    console.error("获取统计信息失败:", error);
    ElMessage.error("获取统计信息失败");
  } finally {
    statisticsLoading.value = false;
  }
};

// 查询排名
const queryRank = async () => {
  try {
    queryLoading.value = true;

    const response = await getRankingPosition(
      queryForm.rankingType as RankingType,
      queryForm.dimension as RankingDimension,
      parseInt(queryForm.targetId),
      queryForm.dimension === "CATEGORY" && queryForm.categoryId
        ? parseInt(queryForm.categoryId)
        : undefined
    );

    // 提取data字段中的实际数据
    rankResult.value = (response as any)?.data || response;
  } catch (error) {
    console.error("查询排名失败:", error);
    ElMessage.error("查询排名失败");
  } finally {
    queryLoading.value = false;
  }
};

// 移除榜单项
const removeRank = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要从所有相关榜单中移除目标 ${removeForm.targetId} 吗？`,
      "确认移除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    removeLoading.value = true;

    await removeRankingItem(
      removeForm.rankingType as RankingType,
      parseInt(removeForm.targetId)
    );

    ElMessage.success("已从所有相关榜单移除");
    removeForm.targetId = "";
    await loadStatistics();
  } catch (error) {
    if (error !== "cancel") {
      console.error("移除榜单项失败:", error);
      ElMessage.error("移除失败");
    }
  } finally {
    removeLoading.value = false;
  }
};

// 更新榜单项
const updateRank = async () => {
  try {
    updateLoading.value = true;

    await updateRankingItem(
      updateForm.rankingType as RankingType,
      parseInt(updateForm.targetId)
    );

    ElMessage.success("榜单数据更新成功");

    // 清空表单
    updateForm.targetId = "";
    await loadStatistics();
  } catch (error) {
    console.error("更新榜单项失败:", error);
    ElMessage.error("更新失败");
  } finally {
    updateLoading.value = false;
  }
};

// 健康检查
const checkHealth = async () => {
  try {
    healthLoading.value = true;

    const response = await getRankingHealth();
    const healthData = (response as any)?.data || response;

    ElMessage.success("排行榜系统健康检查完成");

    // 显示健康检查结果
    ElMessageBox.alert(
      `Redis连接状态: ${healthData?.redisConnected ? "正常" : "异常"}\n` +
        `数据库连接状态: ${healthData?.dbConnected ? "正常" : "异常"}\n` +
        `文章榜状态: ${healthData?.articleRankingHealthy ? "健康" : "异常"}\n` +
        `作者榜状态: ${healthData?.authorRankingHealthy ? "健康" : "异常"}\n` +
        `收藏榜状态: ${healthData?.collectionRankingHealthy ? "健康" : "异常"}\n` +
        `数据完整性: ${healthData?.dataIntegrityPercentage || 0}%\n` +
        `检查时间: ${new Date().toLocaleString()}`,
      "健康检查结果",
      {
        confirmButtonText: "确定",
        type:
          healthData?.redisConnected && healthData?.dbConnected
            ? "success"
            : "error"
      }
    );
  } catch (error) {
    console.error("健康检查失败:", error);
    ElMessage.error("健康检查失败");
  } finally {
    healthLoading.value = false;
  }
};

// 清空所有排行榜
const clearRankings = async () => {
  try {
    await ElMessageBox.confirm(
      "确定要清空所有排行榜数据吗？此操作不可恢复！",
      "确认清空",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    clearLoading.value = true;

    await clearAllRankings();

    ElMessage.success("所有排行榜数据已清空");

    // 清空后重新获取统计信息
    await loadStatistics();
  } catch (error) {
    if (error !== "cancel") {
      console.error("清空排行榜失败:", error);
      ElMessage.error("清空排行榜失败");
    }
  } finally {
    clearLoading.value = false;
  }
};

// 刷新指定榜单
const refreshSingleRanking = async () => {
  try {
    refreshSingleLoading.value = true;

    await refreshRanking(
      refreshForm.rankingType as RankingType,
      refreshForm.dimension as RankingDimension,
      refreshForm.dimension === "CATEGORY" && refreshForm.categoryId
        ? parseInt(refreshForm.categoryId)
        : undefined
    );

    ElMessage.success("榜单刷新成功");
    await loadStatistics();
  } catch (error) {
    console.error("刷新榜单失败:", error);
    ElMessage.error("刷新失败");
  } finally {
    refreshSingleLoading.value = false;
  }
};

// 组件挂载时获取统计信息
onMounted(() => {
  loadStatistics();
});
</script>

<style scoped>
.ranking-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-header p {
  margin: 0;
  font-size: 14px;
  color: #606266;
}

.action-bar {
  margin-bottom: 20px;
}

.action-bar .el-button {
  margin-right: 12px;
}

.statistics-section {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-item {
  padding: 10px;
}

.stat-value {
  margin-bottom: 8px;
  font-size: 28px;
  font-weight: 600;
  color: #409eff;

  &.small {
    font-size: 14px;
    font-weight: 400;
  }
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.query-section,
.operation-section {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.rank-result {
  margin-top: 20px;
}

.rank-info {
  display: flex;
  gap: 8px;
  align-items: center;
}

.rank-label {
  font-weight: 600;
  color: #303133;
}

.rank-value {
  font-size: 16px;
  font-weight: 600;
  color: #67c23a;
}

.rank-value.not-in-rank {
  color: #f56c6c;
}

.rank-status {
  font-size: 14px;
  color: #909399;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}

.el-tabs {
  margin-top: 20px;
}
</style>
